import { Component } from '@angular/core';
import {Observable} from "rxjs";
import {listState} from "../store/reducers/list.reducers";
import {Store} from "@ngrx/store";
import {Service} from "../service/service";
import {deleteBook, loadBooks, addBook as addBookAction} from "../store/actions/book.actions";
import {NzMessageService} from "ng-zorro-antd/message";
import {bookState} from "../store/reducers/book.reducers";
import {Book} from "../store/models/book.model";

@Component({
  selector: 'app-testC',
  templateUrl: './testC.component.html',
  styleUrls: ['./testC.component.less']
})
export class TestCComponent {
  public books$: Observable<any> | undefined;
  public title: string = '';
  public author: string = '';
  public description: string = '';

  constructor(private store: Store<{
                list: listState,books: bookState }>,
              private message: NzMessageService,
              private service: Service) {

  }
  ngOnInit() {
    // 这里代码应该和在一起，但是为了练习，就这样写了。
    this.books$ = this.store.select(state =>{
      return state.books.books
    } );
    this.store.select('books').subscribe((res: any)=>{
      console.log('res', res)
      let id
      if(res.loading){
        id = this.message.loading('Action in progress..', { nzDuration: 0 }).messageId;
      }
      if(!res.loading){
        this.message.remove(id);
      }
    })
  }
  send(){
    this.store.dispatch(loadBooks());
  }
  addBook() {
    const book: Book = {
      title: this.title,
      author: this.author,
      description: this.description,
    };
    // this.store.dispatch(addBookAction({ book }));
    this.store.dispatch(addBookAction({ book }));
    this.title = '';
    this.author = '';
    this.description = '';
  }

  deleteBook(id: number) {
    this.store.dispatch(deleteBook({ id }));
  }
}
